<?
class BaseController {
    /*
     * field_name variable
     */
    var $table;
    var $id_field;
    var $thumb_field;
    var $detail_field;
    var $title_field;
    var $date_field;
    private $array_table_join = array();
    private $array_join_cond = array();
    private $array_join_type = array();
    private $array_field_join_select = array();

    /*
     * value variable
     */
    var $record_id;
    var $thumb;
    var $detail;
    var $title;
    var $date;//date int

    /**
     * @var custom_field
     */
    var $custom_field = array();

    //seo string
    var $seo_string;
    //layout class
    var $layout;
    //template class
    var $template;
    protected $check_record_id = 0;
    public function __construct($id = 0){
        $this->record_id = $id;
        $this->template = new Template();
        $tmp = str_replace('controller','',strtolower(get_class($this)));
        if(file_exists('../template/'.$this->template->tpl_name.'/layout/base_layout.php'))
            require_once '../template/'.$this->template->tpl_name.'/layout/base_layout.php';
        if(file_exists('../template/'.$this->template->tpl_name.'/layout/'.$tmp.'_layout.php')){
            require_once '../template/'.$this->template->tpl_name.'/layout/'.$tmp.'_layout.php';
            $tmp[0] = strtoupper($tmp[0]);
            $layoutname = $tmp.'Layout';
            $this->layout = new $layoutname;
        }
    }

    public function joinTable($table_name, $join_cond = array(), $field_select = array(), $join_type = 'LJ'){
        //parse field select
        if(!is_array($field_select)){
            $field_select = explode(',',$field_select);
        }
        $this->array_table_join[] = $table_name;
        //Điều kiện join : cấu trúc join_cond = array(field_bang_goc=>field_bang_join)
        $this->array_join_cond[$table_name] = $join_cond;
        if(!is_array($field_select)){
            $field_select = array($field_select);
        }
        //loại join : $join_typ = 'LJ - LEFT JOIN, RJ - RIGHT JOIN, IJ - INNER JOIN, SJ - STRAIGHT_JOIN'
        switch($join_type){
            case 'RJ':
                $this->array_join_type[$table_name] = 'RIGHT JOIN';
                break;
            case 'IJ':
                $this->array_join_type[$table_name] = 'INNER JOIN';
                break;
            case 'SJ':
                $this->array_join_type[$table_name] = 'STRAIGHT_JOIN';
                break;
            case 'LJ':
            default :
                $this->array_join_type[$table_name] = 'LEFT JOIN';
                break;
        }
        $this->array_field_join_select[$table_name] = $field_select;
    }

    public function getDataField($field_name = '*'){
        //Xử lý field name
        if($field_name != '*'){
            //Mảng các field dữ liệu
            $array_field_name = explode(',',$field_name);
            //Trường hợp cần lấy nhiều hơn 1 field dữ liệu (pro_name,pro_factory)...
            if(count($array_field_name) > 1){
                $array_return = array();
                //nếu field nào đã có thì loại bỏ field ra khỏi mảng array_field_name
                foreach($array_field_name as $k=>$tmp_name){
                    //loại bỏ dấu cách
                    $tmp_name = trim($tmp_name);
                    //check dữ liệu tồn tại trong các field build sẵn
                    $all_variable_builder = array(
                        $this->thumb_field,
                        $this->detail_field,
                        $this->title_field,
                        $this->date_field);
                    if(in_array($tmp_name,array($all_variable_builder)) && $this->$tmp_name){
                        //gán dữ liệu vào mảng trả về
                        $array_return[$tmp_name] = $this->$tmp_name;
                        //loại bỏ tmp_name đã có ra khỏi mảng fieldname
                        unset($array_field_name[$k]);
                    }
                    //Lấy cache dữ liệu từ custom field
                    if($this->getCustomField($tmp_name) !== NULL){
                        //gán dữ liệu vào mảng trả về
                        $array_return[$tmp_name] = $this->getCustomField($tmp_name);
                        //loại bỏ tmp_name đã có ra khỏi mảng fieldname
                        unset($array_field_name[$k]);
                    }
                }
                //trả lại field_string
                if(count($array_field_name) > 1){
                    $field_string = implode(',',$array_field_name);
                    //query
                    $db = new db_query('SELECT '.$field_string.' FROM '.$this->table.' WHERE '.$this->id_field.' = '.$this->record_id);
                    $result = mysql_fetch_assoc($db->result);unset($db);
                    foreach($result as $k=>$v){
                        $array_return[$k] = $v;
                    }
                }
                return $array_return;
            }
            if(count($array_field_name) == 1){
                $all_variable_builder = array(
                    $this->thumb_field,
                    $this->detail_field,
                    $this->title_field,
                    $this->date_field);

                if(in_array($field_name,array($all_variable_builder)) && $this->$field_name){
                    return $this->$field_name;
                }
                //Lấy cache dữ liệu từ custom field
                if($this->getCustomField($field_name) !== NULL){
                    return $this->getCustomField($field_name);
                }else{
                    $db = new db_query('SELECT '.$this->table.'.'.$field_name.'
                                        FROM '.$this->table.'
                                        WHERE '.$this->id_field.' = '.$this->record_id);
                    $result = mysql_fetch_assoc($db->result);unset($db);
                    $this->setCustomField($field_name,$result[$field_name]);
                    return $result[$field_name];
                }
            }
        }
        if($field_name == '*'){
            if($this->getCustomField('all_data_field')){
                $result = $this->getCustomField('all_data_field');
            }else{
                //nếu có table cần join vào thì add thêm field select
                $str_select_join = '';
                $str_join_table = '';
                if($this->array_table_join){
                    foreach($this->array_table_join as $table_join){
                        foreach($this->array_join_cond[$table_join] as $k=>$v){
                            $str_join_table .= ' '.$this->array_join_type[$table_join].' '
                                .$table_join.' ON '.$this->table.'.'.$k.'='.$table_join.'.'.$v.' ';
                        }
                        //Cac truong query them tu cac bang duoc join
                        foreach($this->array_field_join_select[$table_join] as $field){
                            $str_select_join .= $table_join . '.' . $field . ',';
                        }
                    }

                }
                $select_query_string = $this->table.'.'.$field_name.
                    ($str_select_join ? ','.$str_select_join : '');
                $select_query_string = trim($select_query_string,',');
                $db = new db_query('SELECT '.$select_query_string.'
                                    FROM '.$this->table. '' .
                    $str_join_table.'
                                    WHERE '.$this->id_field.' = '.$this->record_id);
                $result = mysql_fetch_assoc($db->result);unset($db);
                $this->setCustomField('all_data_field',$result);
            }
            if($result){
                $this->check_record_id = $this->record_id;
                //set custom_field
                $this->custom_field = $result;
            }
            if(isset($result[$this->thumb_field]))      $this->thumb    = $result[$this->thumb_field];
            if(isset($result[$this->detail_field]))     $this->detail   = $result[$this->detail_field];
            if(isset($result[$this->title_field]))      $this->title    = $result[$this->title_field];
            if(isset($result[$this->date_field]))       $this->date     = $result[$this->date_field];
            return $result;
        }
    }
    public function getId(){
        return $this->record_id;
    }
    public function loadHeader($extra = ''){
        //ob_clean();
        $html =
            '<!DOCTYPE html>
            <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="vi" lang="vi" xmlns:og="http://ogp.me/ns#" xmlns:fb="https://www.facebook.com/2008/fbml">
            <head>
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />'.$this->seo_string;
        //CSS và JS
        $html .= $this->template->LoadCSS() . $this->template->LoadJS();
        $html .= '</head>' . $extra;
        return $html;
    }
    public function loadFooter($generate_time = 0){
        $footer = '';
        global $DBLog;
        $generate_debug = '';
        if(defined('DEVELOP_ENVIROMENT') && DEVELOP_ENVIROMENT == TRUE && $generate_time){
            $generate_debug = '<div class="develop_debug" style="float :left;width : 100%;padding : 5px;text-align:center;">Generate time : ' . (microtime_float() - $generate_time) .'</div>';
        }
        $footer .= $generate_debug;
        $footer .= $DBLog->showLog();
        $footer .= '</html>';
        ob_end_flush();
        return $footer;
    }
    //check record có tồn tại hay không
    public function recordExists(){
        if($this->record_id <= 0 || $this->check_record_id != $this->record_id){
            return false;
        }
        else{
            return true;
        }
    }
    //trả về ảnh thumb
    public function getThumb(){
        if($this->thumb) return $this->thumb;
        else return $this->getDataField($this->thumb_field);
    }

    /*
     * Lưu kết quả field lấy ra trong mảng custom_field để khi cần lấy lại thì ko cần fai
     * gọi query qua GetDataField nữa
     */
    public function setCustomField($name, $value){
        $this->custom_field[$name] = $value;
        return $this;
    }
    public function getCustomField($name){
        return isset($this->custom_field[$name]) ? $this->custom_field[$name] : NULL;
    }

    public function redirect_error($type){
        switch($type){
            case 404:
                exit('404 - Not found');
                break;

        }
    }
}